/*
 * Copyright 2010 Christoph Widulle (christoph.widulle@googlemail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */



package com.android1.amarena2d.engine;

import com.android1.amarena2d.commons.Recyclable;

public abstract class BaseTimer implements Timer, Recyclable{

    protected float interval;
    protected float elapsed;
    protected int repetition = INFINITE_REPETITION;

    boolean finished = false;
    boolean recycleable = false;

    boolean updateWithTickDelta = false;
    boolean paused;


    public void tick(final float d) {
        if (paused)
            return;
        if (interval == 0 && repetition == INFINITE_REPETITION) {
            if (updateWithTickDelta)
                onTick(d);
            else
                onTick();
        } else {
            elapsed += d;
            if (elapsed >= interval) {
                if (updateWithTickDelta)
                    onTick(d);
                else
                    onTick();
                elapsed = 0;

                if (repetition > 0) {
                    repetition--;
                }
                if (repetition == 0) {
                    finished = true;
                } else {
                    //if timer is running more than once, we want to make it more precise.
                    elapsed -= interval;
                }
            }
        }
    }


    public void onTick() {
    }

    public void onTick(final float d) {
    }

    public boolean isPaused() {
        return paused;
    }

    public void resume() {
        this.paused = false;
    }

    public void pause() {
        this.paused = true;
    }

    public void setRecycleable(boolean recycleable) {
        this.recycleable = recycleable;
    }

    public float getInterval() {
        return interval;
    }

    public boolean isFinished() {
        return finished;
    }

    @Override
    public boolean isRecyclable() {
        return recycleable;
    }

    @Override
    public  void recycle(){

    }

}